package concurrent;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * TODO 简单说明
 *
 * @author yangyang
 * @date 2017/7/14 11:37
 * @email kekecany@163.com
 */
class Sender implements Runnable {

    private PipedWriter pipedWriter = new PipedWriter();
    private Random random = new Random(47);

    public PipedWriter getPipedWriter() {
        return pipedWriter;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                for (char c = 'a'; c < 'z'; c++) {

                    pipedWriter.write(c);

                }
                TimeUnit.MILLISECONDS.sleep(random.nextInt(500));
            }
        } catch (IOException e) {
            System.out.println(e + "sender ioexception");
        } catch (InterruptedException e) {
            System.out.println(e + " sender interrupt");
        }
        System.out.println("exit sender");
    }
}

class Receiver implements Runnable {

    private PipedReader pipedReader;

    public Receiver(Sender sender) throws IOException {
        this.pipedReader = new PipedReader(sender.getPipedWriter());
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                System.out.println("read: " + (char) pipedReader.read() + " ");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public class PipedIO {
    public static void main(String[] args) throws IOException, InterruptedException {
        Sender sender = new Sender();
        Receiver receiver = new Receiver(sender);
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(sender);
        executorService.execute(receiver);
        TimeUnit.SECONDS.sleep(5);
        executorService.shutdownNow();
    }
}
